package com.xin.service.impl;

import com.xin.dao.BookDao;
import com.xin.dao.OrderDao;
import com.xin.dao.OrderItemDao;
import com.xin.dao.impl.BaseDao;
import com.xin.dao.impl.BookDaoimpl;
import com.xin.dao.impl.OrderDaoimpl;
import com.xin.dao.impl.OrderItemDaoimpl;
import com.xin.pojo.*;
import com.xin.service.OrderService;

import java.util.Date;
import java.util.Map;

public class OrderServiceimpl extends BaseDao implements OrderService {
    private OrderDao orderDao=new OrderDaoimpl();
    private OrderItemDao orderItemDao=new OrderItemDaoimpl();
    private BookDao bookDao=new BookDaoimpl();
    /**
     *
     * @param cart
     * @param userId
     * @return 创建订单后，返回订单号
     */
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //创建订单，及保存订单
         String orderId=System.currentTimeMillis()+""+userId;
         Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
         orderDao.saveOrder(order);
         for (Map.Entry<Integer, CartItem> entry:cart.getItems().entrySet()){
             //获取到每个商品项，进行保存
             CartItem cartItem = entry.getValue();
             OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
             orderItemDao.saveOrderItem(orderItem);
             //下单完后，数据库中书的库存，销量对应变化
             Book book = bookDao.queryBookById(cartItem.getId());
             book.setSales(book.getSales()+cartItem.getCount());
             book.setStock(book.getStock()-cartItem.getCount());
         }
         cart.clear();  //清空购物车
        return orderId;
    }
}
